// skin_util.c
#include "skin.h"

// utiities
int 		ptinrect(int x, int y, PSKIN_RECT p)
{
	if (p->x <= x && (p->cx) >= x)
	{
		if (p->y <= y && (p->cy) >= y)
			return 1;
	}
	return 0;
}

PSKIN_CLIENT skin_pt_in_client(PSKIN_WINDOW wnd, int x, int y)
{
	PSKIN_CLIENT p = wnd->clients;
	while (p)
	{
		if (ptinrect(x, y, &p->rect))
			return p;
		p = p->next;
	}
	return 0;
}

int 		skin_send_event(int event, PSKIN_CLIENT p)
{
	SDL_Event    e;
    if (p)
    {
        e.type 			= event;
        e.user.data1 	= p;
        e.user.code 	= p->client_id;
        SDL_PushEvent(&e);
    }
}

void        skin_windowupdate(PSKIN_WINDOW p)
{
    SDL_Event    e;
    if (p)
    {
        e.type = SKIN_EVENT_REFRESH;
        e.user.data1 = p;
        SDL_PushEvent(&e);
    }
}

void        skin_set_activecontrol(PSKIN_WINDOW p, PSKIN_CLIENT control)
{
    if (p)
    {
        p->active = control;
    }
}

int 		skin_create_font(PSKIN_WINDOW p, const char* font_name, int font_size)
{
	if (p)
	{
#if (SDL_TTF_USE == 1)
		p->default_font = TTF_OpenFont(font_name, font_size);
		if (p->default_font)
		{
#if (SKIN_DEBUG == 1)
			printf("Font create\r\n");
#endif
			return 1;
		}
#endif
	}
	return 0;
}

int skin_wait_close(PSKIN_WINDOW pwnd)
{
    int done = 0;
    int ret = 0;
    if (pwnd && pwnd->skin_proc)
        pwnd->skin_proc(pwnd, SKIN_EVENT_INITWIN, 0, 0);

    while (pwnd && !done)
    {
        while (SDL_PollEvent(&pwnd->event))
        {
            switch (pwnd->event.type)
            {
            case SDL_QUIT:
                pwnd->OnCloseWindow(pwnd);
                done = 1;
                break;
            // button
            case SKIN_COMMAND:
                {
                    pwnd->OnCommand((int)pwnd->event.user.code, (PSKIN_CLIENT)pwnd->event.user.data1);
                }
                break;
            case SDL_ACTIVEEVENT:
            case SDL_KEYDOWN:
            case SDL_KEYUP:
            case SDL_MOUSEMOTION:
            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP:
            case SDL_JOYAXISMOTION:
            case SDL_JOYBALLMOTION:
            case SDL_JOYHATMOTION:
            case SDL_JOYBUTTONDOWN:
            case SDL_JOYBUTTONUP:
            case SDL_SYSWMEVENT:
            case SDL_VIDEORESIZE:
            case SDL_VIDEOEXPOSE:
            case SKIN_EVENT_REFRESH:                    
            default:
                if (pwnd->skin_proc)
                    ret = pwnd->skin_proc(pwnd, pwnd->event.type, 0, &pwnd->event);
                break;
            }
        }
        usleep(1000*500);
    }

    if (pwnd)
        skin_closewindow(pwnd);
  return 0;
}